package com.h2.ref.server.web.user;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.h2.common.util.email.impl.SmtpUtils;

public class UserValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      if (clazz.isAssignableFrom(UserFormData.class)) {
         return true;
      }
      else {
         return false;
      }
   }

   @Override
   public void validate(Object obj, Errors binding) {
      UserFormData user = (UserFormData)obj;
      validateName(user.getName(), binding);
      validateEmail(user.getUserDetails().getEmail(), binding);
      validateEmailConfirm(user.getUserDetails().getEmail(),
            user.getEmailConfirm(), binding);
      validatePassword(user.getPassword(), binding);
      validateCode(user.getVerificationCode(), binding);
   }
   
   public static void validateName(String name, Errors binding) {
      if (!StringUtils.hasLength(name)) {
         // userName
         binding.rejectValue("name", "register.user.invalid");
      }
      else if (SmtpUtils.isAddressValid(name)) {
         binding.rejectValue("name", "register.user.email.disallowed.error");
      }
   }
   
   public static void validatePassword(String password, Errors binding) {
      if (!StringUtils.hasLength(password)) {
         // password
         binding.rejectValue("password", "register.password.required");
      }
   }
   
   public static void validateEmail(String email, Errors binding) {
      if (!SmtpUtils.isAddressValid(email)) {
         binding.rejectValue("userDetails.email", "register.email.invalid.format");
      }
   }
   
   public static void validateEmailConfirm(String email, String emailConfirm,
         Errors binding) {
      if (!SmtpUtils.isAddressValid(emailConfirm)) {
         binding.rejectValue("emailConfirm", "register.email.invalid.format");
      }
      else if(!email.equals(emailConfirm)) {
         binding.rejectValue("emailConfirm", "register.email.invalid.match");
      }
   }
   
   public static void validateCode(String code, Errors binding) {
      if(!"xcom rocks".equals(code)) {
         binding.rejectValue("verificationCode",
               "register.verificationCode.invalid");
      }
   }

}
